package Niuke;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;



//应该是sout函数没有同步，所以结果有点不太对
//深入浅出多线程pdf上说的
public class BlockingQueue2consumer {
    private BlockingQueue queue=new ArrayBlockingQueue(10);

    //consumer
     class consumer implements Runnable{

        @Override
        public void run() {
            while (true){
                try {
                    queue.take();
                    System.out.println("取走一个元素，剩余："+queue.size());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //produer
     class producer implements Runnable{

        @Override
        public void run() {
                while (true){
                    try {
                        queue.put(1);
                        System.out.println("放进去一个元素，共有："+queue.size());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue2consumer b=new BlockingQueue2consumer();

        consumer consumer = b.new consumer();
        producer producer1 = b.new producer();

        ThreadPoolExecutor e= (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
        e.execute(consumer);
        e.execute(producer1);

        Thread.sleep(100);
        e.shutdownNow();
    }
}
